package com.ry.aspect;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.ry.aspect.annotation.ParamDeal;
import com.ry.config.BaseEntity;

/**
 * 设置 超类的language，用于字典查询
 * @author Administrator
 *
 */
@Aspect
@Component
public class ParamAspect {

	// 配置织入点
	@Pointcut("@annotation(com.ry.aspect.annotation.ParamDeal)")
	public void doOperation() {

	}

	@Before(value = "doOperation()")
	public void dealParam(JoinPoint point) {
		ParamDeal paramDeal = getAnnotationLog(point);
		System.out.println(paramDeal.useDict());
		boolean useDict = paramDeal.useDict();
		if(!useDict) {
			return;
		}
		
		ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = servletRequestAttributes.getRequest();
		String language = request.getHeader("Accept-Language");

		Object params0 = point.getArgs()[0];
		if (params0 instanceof BaseEntity) {
			BaseEntity baseEntity = (BaseEntity) point.getArgs()[0];
			baseEntity.setDictLanguage(language);
		}

	}

	/**
	 * 是否存在注解，如果存在就获取
	 */
	private ParamDeal getAnnotationLog(JoinPoint joinPoint) {
		Signature signature = joinPoint.getSignature();
		MethodSignature methodSignature = (MethodSignature) signature;
		Method method = methodSignature.getMethod();

		if (method != null) {
			return method.getAnnotation(ParamDeal.class);
		}
		return null;
	}

	public static void main(String[] args) {
		
		
		
	}
	
}
